import { defineStore } from "pinia";
import { ref } from "vue";
import { loginAPI, logOut } from "@/apis/user";
import { useCarStore } from './car'
import { mergeCarAPI } from "@/apis/car";
import { getFaceAuth, getUserAuth } from "@/apis/auth";

export const userInfoStore = defineStore('user', () => {
    //state
    const userInfo = ref({})
    const resData = ref({})
    const carStore = useCarStore()

    // 状态变量
    const personalAuthStatus = ref(false); // 个人认证状态
    const faceAuthStatus = ref(false); // 人脸识别状态

    const getUserAuthStatus = async () => {
        const res = await getUserAuth();
        console.log("res: ", res);
        personalAuthStatus.value = res.data;
    };
    const getFaceAuthStatus = async () => {
        const res = await getFaceAuth();
        console.log("res: ", res);
        faceAuthStatus.value = res.data;
    };

    //action
    const getUserInfo = async ({ captchaKey },
        { username, password, vcode }) => {

        const res = await loginAPI(
            { captchaKey },
            { username, password, vcode }
        );
        resData.value = res
        console.log('res.data.user: ', res.data.user);
        userInfo.value = res.data.user
        // await mergeCarAPI(carStore.cartList.map(item => {
        //     return {
        //         skuId: item.skuId,
        //         selected: item.selected,
        //         count: item.count
        //     }
        // }))
        carStore.updateCarList()
        // getUserAuthStatus();
        // getFaceAuthStatus();
    }

    const clearUserInfo = async () => {
        await logOut()
        userInfo.value = {}
        carStore.clearCar()
    }

    const checkAuthStatus = async () => {
        await getUserAuthStatus();
        await getFaceAuthStatus();
        return personalAuthStatus.value && faceAuthStatus.value;
    };

    return {
        getUserInfo,
        clearUserInfo,
        userInfo,
        resData,
        getUserAuthStatus,
        getFaceAuthStatus,
        checkAuthStatus
    }
}, {
    persist: true,
}) 
